<template>
	<div>
		<el-form :model="taskParam" :validate-on-rule-change="false" label-width="90px" :rules="isTestings?rules:{}"
			ref="ruleFormRef">
			<el-form-item label="审批结果" style="width: 100%;" prop="approveAdvice">
				<el-radio-group v-model="taskParam.approveAdvice">
					<el-radio :label="1">同意</el-radio>
					<el-radio v-if="disagreeShow" :label="4">不同意</el-radio>
					<el-radio v-if="retractRecordData.length > 0" :label="0">退回</el-radio>
				</el-radio-group>
			</el-form-item>
			<div style="width: 100%;" v-if="retractDialogVisible && retractRecordData.length > 1">
				<el-form-item label="退回节点">
					<el-select v-model="retractNodeKey" placeholder="请选择" style="width:25%;">
						<el-option v-for="item in  retractRecordData" :key="item.actId" :label="item.actName"
							:value="item.actId">
						</el-option>
					</el-select>
				</el-form-item>
			</div>
			<el-form-item label="处理意见" style="width: 100%;" prop="discicription">
				<el-input type="textarea" :rows="4" placeholder="请输入内容" maxlength="1000" show-word-limit
					v-model="taskParam.discicription">
					<template #append>
						<el-button icon="ele-FolderChecked" v-if="tempSaveButtonShow" @click="saveApproveAdviceText"
							:loading="saveApproveAdviceLoaing">暂存</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="流程附件">
				<FileUpload :businessId="taskId" style="width: 100%"></FileUpload>
			</el-form-item>
		</el-form>
		<footer class="el-dialog__footer" style="text-align:center">
			<span class="dialog-footer">
				<el-button @click="refreshEmit()" icon="ele-Close">关闭</el-button>
				<el-button type="primary" icon="ele-Check" @click="dataFormSubmit(ruleFormRef)">提交
				</el-button>
				<el-button type="primary" @click="tip()" icon="ele-Delete">终止
				</el-button>
			</span>
		</footer>
	</div>
</template>
<script lang="ts">
import { ref, toRefs, reactive, watch, defineComponent, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading, FormInstance } from 'element-plus'
import FileUpload from '/@/components/fileUpload/index.vue'
import { workflowApi } from '/@/api/workflowapi'
export default defineComponent({
	props: {
		modelValue: {
			type: Object,
			required: true
		},
		taskId: {
			type: String,
			required: true
		},
		processId: {
			type: String,
			required: true
		},
		busNo: {
			type: String,
			required: true
		},
		isUpload: {
			type: Boolean,
			default: true
		},
		disagreeShow: {
			type: Boolean,
			default: false
		},
		authCatagory: {
			type: String,
			default: '0'
		},
		owner: {
			type: String,
			default: ''
		},
		tempSaveButtonShow: {
			type: Boolean,
			default: false
		}
	},
	components: { FileUpload },
	emits: ['update:modelValue', 'refreshEmit', 'dataFormSubmit'],
	setup(props, ctx) {
		const ruleFormRef = ref<FormInstance>()
		const state = reactive({
			isTestings: true,
			//流程相关表单数据
			taskParam: {
				taskId: props.taskId,
				busNo: props.busNo,
				discicription: '', //审批意见
				processKey: '',
				approveAdvice: '',//审批结果
				briefReport: '',//流程摘要,业务发起流程传入
				skipFirstNode: true,
				wf_param: {},
				variablesLocal: {},
				authCatagory: props.authCatagory,
				owner: props.owner,// 授权人，从授权处理的流程点击进来的这个值为授权人
				formProperties: {},
				insId: props.processId
			},
			rules: {
				approveAdvice: [
					{ required: true, message: '请选择审批结果', trigger: 'blur' }
				],
				discicription: [
					{ required: true, message: '请填写意见', trigger: 'blur' }
				]
			},
			retractDialogVisible: false,
			retractRecordData: [],
			selectReatracNode: null,
			retractNodeKey: null,
			saveApproveAdviceLoaing: false,
		})
		// 页面加载时
		onMounted(() => {
			ruleFormRef.value?.resetFields()
			state.taskParam.taskId = props.taskId
			state.taskParam.busNo = props.busNo
			state.taskParam.authCatagory = props.authCatagory
			state.taskParam.owner = props.owner
			state.taskParam.insId = props.processId
			retract()
		})
		const retract = () => {
			state.retractRecordData = []
			workflowApi().getRetractNodeByTaskId(props.taskId).then((data) => {
				if (data.code === 0) {
					state.retractRecordData = data.result
					if (state.retractRecordData.length === 1) {
						state.selectReatracNode = state.retractRecordData[0]
						state.retractNodeKey = state.retractRecordData[0].actId
					} else if (state.retractRecordData.length === 0) {
						state.selectReatracNode = null
					}
				}
			}).catch(() => {
			})
		}
		const saveApproveAdviceText = () => {
			//暂存审批意见
			state.saveApproveAdviceLoaing = true
			workflowApi().saveApproveAdvice(props.taskId, state.taskParam.approveAdvice, state.taskParam.authCatagory, state.taskParam.owner).then((data) => {
				if (data.code === 0) {
					ElMessage.success('暂存审批意见成功')
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(() => {
				ElMessage.error('暂存审批意见出错')
			}).finally(() => {
				state.saveApproveAdviceLoaing = false
			})
		}
		watch(() => state.taskParam.approveAdvice, (val) => {
			if (val === 0) {
				state.retractDialogVisible = true
				state.taskParam.discicription = '退回'
				state.isTestings = true
			} else if (val === 1) {
				state.isTestings = false
				state.retractDialogVisible = false
				state.taskParam.discicription = '同意'
			} else if (val === 4) {
				state.isTestings = false
				state.retractDialogVisible = false
				state.taskParam.discicription = '不同意'
			}
		})
		watch(() => state.retractNodeKey, (val) => {
			for (let i = 0; i < state.retractRecordData.length; i++) {
				if (state.retractRecordData[i].actId === val) {
					state.selectReatracNode = state.retractRecordData[i]
					return
				}
			}
		})
		
		//关闭
		const refreshEmit = () => {
			ctx.emit('refreshEmit')
		}
		//提交流程
		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					if (state.taskParam.approveAdvice !== 0) {
						//提交流程
						ctx.emit('dataFormSubmit', state.taskParam)
					} else {
						const loading = ElLoading.service({
							lock: true,
							text: '处理中',
							background: 'rgba(0, 0, 0, 0.7)',
						})
						//退回流程
						workflowApi().submitretract({
							'taskId': state.taskParam.taskId,
							'activityDfId': state.selectReatracNode.activityDfId,
							'userId': state.selectReatracNode.assignee,
							'approveAdvice': state.taskParam.approveAdvice,
							'discicription': state.taskParam.discicription
						}).then((data) => {
							if (data.code === 0) {
								ElMessage.success('退回流程成功')
								ctx.emit('refreshEmit')
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('退回流程失败')
						}).finally(() => {
							loading.close()
						})
					}
					
				}
			})
		}
		//终止流程
		const tip = () => {
			ElMessageBox.prompt('请输入终止原因', '终止', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(({ value }) => {
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				workflowApi().deleteProcess({
					'processid': props.processId,
					'deleteReason': value
				}).then((data) => {
					if (data.code === 0) {
						ElMessage.success('成功终止')
						ctx.emit('refreshEmit')
					} else {
						ElMessage.error("终止失败！")
					}
				}).catch(() => {
					ElMessage.error("终止失败！")
				}).finally(() => {
					loading.close()
				})
			}).catch(() => {
			})
		}
		return {
			ruleFormRef,
			saveApproveAdviceText,
			refreshEmit,
			dataFormSubmit,
			tip,
			retract,
			...toRefs(state),
		}
	},
})
</script>
<style lang="less" scoped>

</style>